package com.newthread.android.mail;

import android.util.Log;


import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Date;
import java.util.Properties;

/**
 * Created by 翌日黄昏 on 13-11-21.
 */
public class MailSender {

    private MailSetting mailSetting;

    public MailSender() {
        this.mailSetting = null;
    }

    public MailSender(MailSetting mailSetting) {
        this.mailSetting = mailSetting;
    }

    /**
     * 发送文本邮件
     *
     * @param mailMs 待发送邮件的消息
     */
    public void sendMail(final MailMs mailMs, final CallBack callBack) {

        new Thread() {
            public void run() {

                Properties props = new Properties();
                props.put("mail.smtp.starttls.enable", "true");
                if( mailSetting == null){
                    callBack.sendState("no host");
                    return;
                }
                props.put("mail.smtp.host", mailSetting.getHost());
                props.put("mail.smtp.port", mailSetting.getPort());
                props.put("mail.smtp.auth", "true");
                MyAuthenticator authenticator = new MyAuthenticator(mailMs.getMailAuthor().getAddress(),
                        mailMs.getMailAuthor().getPassword());
                Log.i("Check", "done pops");
                // 根据邮件会话属性和密码验证器构造一个发送邮件的session
                Session session = Session.getDefaultInstance(props, authenticator);

                try {
                    javax.mail.Message mailMessage = new MimeMessage(session);
                    // 创建邮件发送者地址
                    Address from = new InternetAddress(mailMs.getMailAuthor().getAddress());
                    // 设置邮件消息的发送者
                    mailMessage.setFrom(from);
                    // 创建邮件的接收者地址，并设置到邮件消息中
                    Address[] tos = tos = new InternetAddress[1];
                    tos[0] = new InternetAddress(mailMs.getTo());
                    // Message.RecipientType.TO属性表示接收者的类型为TO
                    mailMessage.setRecipients(javax.mail.Message.RecipientType.TO, tos);
                    // 设置邮件消息的主题
                    mailMessage.setSubject(mailMs.getMailContent().getSubject());
                    // 设置邮件消息发送的时间
                    mailMessage.setSentDate(new Date());
                    // 设置邮件消息的主要内容
                    String mailContent = mailMs.getMailContent().getContent();
                    mailMessage.setText(mailContent);
                    if (mailMs.getMailContent().getAttachmentfinal() != null
                            && !mailMs.getMailContent().getAttachmentfinal().equals("")) {
                        if ((new File(mailMs.getMailContent().getAttachmentfinal())).exists()) {
                            mailMessage.setContent(getAttachment(mailMs.getMailContent().getAttachmentfinal()));
                        }
                    }
                    // 发送邮件
                    if (callBack != null)
                        callBack.sendState("sending");
                    Transport.send(mailMessage);
                    if (callBack != null)
                        callBack.sendState("sended");
                } catch (MessagingException e) {
                    if (callBack != null)
                        callBack.sendState("send fail");
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private MimeMultipart getAttachment(String filePath) {
        MimeBodyPart attachPart = new MimeBodyPart();
        FileDataSource file = new FileDataSource(filePath); //打开要发送的文件
        MimeMultipart mimeMultipart = null;

        try {
            attachPart.setDataHandler(new DataHandler(file));
            attachPart.setFileName(file.getName());
            mimeMultipart = new MimeMultipart("mixed"); //附件
            mimeMultipart.addBodyPart(attachPart);//添加
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return mimeMultipart;
    }

    public MailSetting getMailSetting() {
        return mailSetting;
    }

    public void setMailSetting(MailSetting mailSetting) {
        this.mailSetting = mailSetting;
    }

    public interface CallBack {
        void sendState(String state);
    }
}
